import 'package:flutter/material.dart';
import 'package:gold/app/user_provider.dart';
import 'package:gold/utils/xfg_extension.dart';
import 'package:gold/widgets/http_image.dart';
import 'package:provider/provider.dart';
import 'package:pull_to_refresh_flutter3/pull_to_refresh_flutter3.dart';
import 'package:waterfall_flow/waterfall_flow.dart';
import 'package:gold/app/app.dart';
import 'package:gold/base/provider_widget.dart';
import 'package:gold/route/routes.dart';
import 'package:gold/route/xfg_nav.dart';
import 'package:gold/ui/home/home_viewmodel.dart';
import 'package:gold/utils/res.dart';
import 'package:gold/utils/xfg_color.dart';
import 'package:gold/utils/xfg_size.dart';
import 'package:gold/utils/xfg_utils.dart';
import 'package:gold/widgets/oval_image.dart';
import 'package:gold/widgets/xfg_text.dart';

/// @description:
/// @author tangzhentao
/// @created at 21:38 2024/11/25

class HomePage extends StatefulWidget {
  const HomePage({super.key});

  @override
  State<StatefulWidget> createState() => _HomeState();
}

class _HomeState extends State<HomePage> with AutomaticKeepAliveClientMixin {

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return ProviderWidget<HomeViewmodel>(
        model: HomeViewmodel(),
        onInit: (data) => data.loadFirst(),
        stackChildren: [OvalImage(Res.imagesHomeTop, size: Size(XfgSize().screenWidth, XfgSize().size236))],
        builder: (ctx, home) => Padding(
          padding: EdgeInsets.symmetric(horizontal: XfgSize().size10),
          child: SmartRefresher(
            controller: home.controller,
            enablePullUp: true,
            enablePullDown: true,
            onRefresh: () => home.refresh(),
            onLoading: () => home.loadMore(),
            child: CustomScrollView(
              slivers: [
                /// 应用名称
                SliverToBoxAdapter(
                  child: Container(
                    margin: EdgeInsets.only(top: XfgSize().statusBarHeight),
                    alignment: Alignment.centerLeft,
                    child: XfgText(App.appName, color: XfgColor.white, fontSize: XfgSize().text24, bold: FontWeight.bold, fontStyle: FontStyle.italic),
                  ),
                ),
                /// 金价信息
                SliverToBoxAdapter(
                  child: Container(
                    margin: EdgeInsets.only(top: XfgSize().size10),
                    height: XfgSize().size220,
                    width: XfgSize().size355,
                    child: Stack(
                      children: [
                        Container(
                          height: XfgSize().size48,
                          padding: EdgeInsets.symmetric(horizontal: XfgSize().size10, vertical:  XfgSize().size14),
                          decoration: BoxDecoration(color: XfgColor.homeTop, borderRadius: BorderRadius.vertical(top: Radius.circular(XfgSize().size6))),
                          child: Row(
                            crossAxisAlignment: CrossAxisAlignment.end,
                            children: [
                              XfgText('实时报价', fontSize:  XfgSize().text18, color: XfgColor.homeRealPrice),
                              const Spacer(),
                              XfgText(ctx.select<UserProvider, GoldQuotes?>((k) => k.goldQuotes)?.date?? '', fontSize:  XfgSize().text14, color: XfgColor.homeRealPriceValue),
                              SizedBox(width: XfgSize().size10)
                            ],
                          ),
                        ),
                        Align(
                          alignment: Alignment.bottomCenter,
                          child: Container(
                            height: XfgSize().size175,
                            decoration: BoxDecoration(color: XfgColor.white, borderRadius: BorderRadius.circular(XfgSize().size6)),
                            child: GestureDetector(
                              onTap: () => XfgNav.pushNamed(Routes.realTimeQuotes),
                              behavior: HitTestBehavior.opaque,
                              child: Builder(builder: (con) {
                                final quotes = con.select<UserProvider, GoldQuotes?>((k) => k.goldQuotes);
                                return Column(
                                  children: [
                                    SizedBox(height: XfgSize().size18),
                                    XfgText('今日金价（元）', fontSize: XfgSize().text16, color: XfgColor.text1),
                                    // SizedBox(height: XfgSize().size6),
                                    GestureDetector(
                                      behavior: HitTestBehavior.translucent,
                                      child:Row(
                                        crossAxisAlignment: CrossAxisAlignment.end,
                                        children: [
                                          const Spacer(),
                                          XfgText(quotes?.map[realTimeGoldPrice]?.lastPrice?? '0.00', fontSize: XfgSize().text40, color: XfgColor.theme, bold: FontWeight.bold),
                                          Expanded(
                                            child: Container(
                                              alignment: Alignment.bottomRight,
                                              padding: EdgeInsets.only(right: XfgSize().size30, bottom: XfgSize().size14),
                                              child: OvalImage(Res.imagesArrowRight, size: Size(XfgSize().size10, XfgSize().size15)),
                                            ),
                                          )
                                        ],
                                      ),
                                    ),
                                    const Spacer(),
                                    SizedBox(
                                      height: XfgSize().size64,
                                      child: Row(
                                        children: [
                                          _topItemWidget('黄金9999', quotes?.map['1053']?.lastPrice?? '0.00'),
                                          _topItemWidget('黄金T+D', quotes?.map['1051']?.lastPrice?? '0.00'),
                                          _topItemWidget('黄金其他', quotes?.map['1059']?.lastPrice?? '0.00')
                                        ],
                                      ),
                                    ),
                                  ],
                                );
                              }),
                            ),
                          ),
                        )
                      ],
                    ),
                  ),
                ),
                /// 功能信息
                SliverToBoxAdapter(
                  child: Container(
                    margin: EdgeInsets.symmetric(vertical: XfgSize().size10),
                    height: XfgSize().size114,
                    width: XfgSize().size355,
                    decoration: BoxDecoration(color: XfgColor.white, borderRadius: BorderRadius.circular(XfgSize().size6)),
                    child: Row(
                      children: [
                        _functionItemWidget('黄金回收', Res.imagesHomeGoldRecover, onTap: () => toGoldRecovery()),
                        _functionItemWidget('黄金投资', Res.imagesHomeGoldInvest, onTap: () => XfgNav.pushNamed(Routes.goldInvest)),
                        _functionItemWidget('排行榜', Res.imagesHomeRank, onTap: () => XfgNav.pushNamed(Routes.rank)),
                        _functionItemWidget('我要赚钱', Res.imagesHomeShare, onTap: () => XfgNav.pushNamed(Routes.myInvite)),
                      ],
                    ),
                  ),
                ),
                /// 商品信息
                SliverWaterfallFlow(
                  gridDelegate: SliverWaterfallFlowDelegateWithFixedCrossAxisCount(
                      crossAxisCount: 2, mainAxisSpacing: XfgSize().size10, crossAxisSpacing: XfgSize().size10
                  ),
                  delegate: SliverChildBuilderDelegate((ctx, index) {
                    final goods = home.goodsList[index];
                    final reward = '${goods.rewardPoints?.replaceAll('.00', '')?? ''}积分';
                    final prices = goods.price?.split(('.'));
                    return GestureDetector(
                      onTap: () {
                        final id = goods.id;
                        if (id != null) {
                          XfgNav.pushNamed(Routes.goodsDetail, arguments: id);
                        } else {
                          '商品信息缺失'.toast();
                        }
                      },
                      child: ClipRRect(
                        borderRadius: BorderRadius.circular(XfgSize().size6),
                        child: Container(
                          color: XfgColor.white,
                          child: Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: <Widget>[
                              HttpImage(goods.coverImage, size: Size(double.infinity, XfgSize().size175)),
                              Padding(
                                padding: EdgeInsets.all(XfgSize().size10),
                                child: XfgText(goods.name?? '', fontSize: XfgSize().text14, color: XfgColor.text1),
                              ),
                              Padding(
                                padding: EdgeInsets.fromLTRB(XfgSize().size10, 0, XfgSize().size10, XfgSize().size10),
                                child: Row(
                                  children: [
                                    XfgText('￥', fontSize: XfgSize().text12, color: XfgColor.itemMoney, children: [
                                      TextSpan(text: '${prices?.first?? ''}.', style: TextStyle(fontSize: XfgSize().text20)),
                                      TextSpan(text: prices?.last?? '')
                                    ]),
                                    const Spacer(),
                                    Container(
                                      decoration: BoxDecoration(
                                          borderRadius: BorderRadius.circular(XfgSize().size2),
                                          border: Border.all(color: XfgColor.itemIntegration, width: XfgSize().size0_5)
                                      ),
                                      width: XfgSize().size10 + xfgBoundingTextSize(reward, style: TextStyle(fontSize: XfgSize().text12)).width,
                                      height: XfgSize().size18,
                                      alignment: Alignment.center,
                                      child: XfgText(reward, fontSize: XfgSize().text12, color: XfgColor.itemIntegration),
                                    )
                                  ],
                                ),
                              ),
                            ],
                          ),
                        ),
                      ),
                    );
                  }, childCount: home.goodsList.length),
                )
              ],
            ),
          ),
        )
    );
  }

  /// 金价信息
  Widget _topItemWidget(String title, String value) => Expanded(
      child: Column(
        mainAxisSize: MainAxisSize.max,
        children: [
          XfgText(title, fontSize: XfgSize().text14, color: XfgColor.text1),
          SizedBox(height: XfgSize().size3),
          XfgText('¥', fontSize: XfgSize().text12, color: XfgColor.homeGoldSmall,children: [
            TextSpan(text: value, style: TextStyle(fontSize: XfgSize().text20, color: XfgColor.homeGoldLarge))
          ])
        ],
      )
  );

  /// 功能信息
  Widget _functionItemWidget(String title, String image, {GestureTapCallback? onTap}) => Expanded(
    child: InkWell(
      onTap: onTap,
      child:  Column(
        mainAxisSize: MainAxisSize.max,
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          OvalImage(image, size: Size.square(XfgSize().size40)),
          SizedBox(height: XfgSize().size12),
          XfgText(title, fontSize: XfgSize().text14, color: XfgColor.text1)
        ],
      ),
    ),
  );

  @override
  bool get wantKeepAlive => true;
}


